<template>
  <div class="history-container">
    <van-tabbar :active="activeName" :fixed="false" @change="handleSwitch">
      <van-tabbar-item
        v-for="action in actions"
        :key="action.name"
        :name="action.name"
        :icon="action.src"
      >
        {{ action.text }}
      </van-tabbar-item>
    </van-tabbar>
    <van-collapse :value="activeTabs" @change="evt => activeTabs = evt.mp.detail">
      <van-collapse-item
        v-for="(item, idx) in formatedHistory"
        :disabled="item.list.length === 0"
        :key="idx"
        :name="idx"
      >
        <view slot="title" class="tab-title">
          <van-icon
            size="20px"
            :name="item.src"
            style="margin-right: .5rem;"
            :info="item.list.length"
          />
          <span>{{ item.text }}</span>
        </view>
        <van-cell-group>
          <van-cell
            v-for="(data, idx2) in item.list"
            :key="idx2"
            :title="data.text"
            :label="data.date"
            :value="data.area || '不限地区'"
          />
        </van-cell-group>
      </van-collapse-item>
    </van-collapse>
  </div>
</template>

<script>
import { formatTime } from '@/utils/index'
import card from '@/components/card'
import { ACTION_TYPES, STATUS_TYPES } from '@/constant'

export default {
  components: {
    card
  },

  data () {
    return {
      history: [],
      activeName: 'heart',
      activeTabs: [],
      actions: ACTION_TYPES()
    }
  },

  computed: {
    formatedHistory () {
      const { history } = this
      return history.reduce((acc, item) => {
        const { status = 0 } = item
        acc[status].list.push({
          ...item,
          date: formatTime(item.timestamp)
        })
        return acc
      }, STATUS_TYPES())
    }
  },

  methods: {
    formatTime,
    getList () {
      const { activeName: name } = this
      wx.cloud.init()
      const db = wx.cloud.database()
      let self = this
      db
        .collection('history')
        .where({
          _openid: 'user-open-id',
          name
        })
        .get()
        .then(({ data }) => {
          console.log(data)
          self.history = data
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleSwitch (evt) {
      const name = evt.mp.detail
      this.activeName = name
      this.getList()
    }
  },

  mounted () {
    this.getList()
  }
}
</script>

<style lang="scss">
.log-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}

.tab-title {
  display: flex;
  align-items: center;
}

.log-item {
  margin: 10rpx;
}
</style>
